package com.pospi.xstore.ui.count;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.CountSAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.CashierMsgDto;
import com.pospi.xstore.dto.CountBeen;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.greendao.CountBeenDao;
import com.pospi.xstore.ui.CaptureActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.cash_ui.ScanReceiptActivity;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.PareseJson;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.view.swipemenulistview.SwipeMenu;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuCreator;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuItem;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CountActivity extends BaseActivity {

    @Bind(R.id.iv_search_counts)
    ImageView iv_search_counts;
    @Bind(R.id.iv_scan_counts)
    ImageView iv_scan_counts;
    @Bind(R.id.counts_start)
    TextView counts_start;

    @Bind(R.id.lv_goods_counts)
    SwipeMenuListView lv_goods_counts;
    @Bind(R.id.et_code_counts)
    EditText et_code_counts;
    @Bind(R.id.count_date)
    TextView count_date;
    @Bind(R.id.activity_count)
    LinearLayout parent;

    private List<GoodsDto> goodsDtos = new ArrayList<>();
    private CountSAdapter sAdapter;
    private GoodsDao dao;
    private CountBeenDao countBeenDao;
    private String time;
    private GoodsDto gd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_counts);
        setTitle("开始盘点");
        setMenuText("清空");
        ButterKnife.bind(this);
        time = getIntent().getStringExtra("date");
        count_date.setText(time);
        dao = new GoodsDao(getApplicationContext());
        countBeenDao = App.getInstance().getDaoSession().getCountBeenDao();
        init();
    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        if (goodsDtos.size() == 0) {
            Toast.makeText(CountActivity.this, "数据为空", Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("是否清空数据？");
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goodsDtos.clear();
                sAdapter.notifyDataSetChanged();
            }
        });
        dialog.setNeutralButton("取消", null);
        dialog.show();


    }

    @Override
    protected void onStart() {
        super.onStart();
        et_code_counts.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.i("num", "ooo");
                search(et_code_counts.getText().toString().trim());
                return false;
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        adapteData(GetData.getYYMMDDTime());

    }
    private void init() {
        sAdapter = new CountSAdapter(this, goodsDtos);
        lv_goods_counts.setAdapter(sAdapter);
        iv_search_counts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search(et_code_counts.getText().toString().trim());


            }
        });
        lv_goods_counts.setOnItemClickListener(new AdapterView.OnItemClickListener() {



            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                gd = goodsDtos.get(i);
                showInput();
            }
        });
        iv_scan_counts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestCemera();
            }
        });
        counts_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (goodsDtos.size() == 0) {
                    Toast.makeText(CountActivity.this, "数据为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                new AlertDialog.Builder(CountActivity.this)
                        .setTitle("提示")
                        .setMessage("是否保存")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //保存
                                save();
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();



            }
        });
        setSwipeListView();
    }
    private void requestCemera() {
        if (PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)) {
            //有访问摄像头的权限
            //扫描
            Intent intent = new Intent(CountActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问摄像头的权限
                    //扫描
                    Intent intent = new Intent(CountActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, 1);
                }


                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问摄像头的申请
                }
            }, new String[]{Manifest.permission.CAMERA});
        }
    }
    private void save() {
        if (goodsDtos.size() != 0) {
            int which = getSharedPreferences("islogin", Context.MODE_PRIVATE).getInt("which", 0);
            List<CashierMsgDto> cashierMsgDtos = new PareseJson().parese(getSharedPreferences("cashierMsgDtos", Context.MODE_PRIVATE).getString("cashierMsgDtos", ""));
            String name = cashierMsgDtos.get(which).getName();
            String detail = SaveOrderInfo.changeGoodDtoToJson(goodsDtos);
            CountBeen countBeen = new CountBeen();
            countBeen.setMId(GetData.getStringRandom(4)+GetData.getYYMMDDHHMMTime());
            countBeen.setMCountId(GetData.getYYMMDDNoSpellingTime() + GetData.getStringRandom(4));
            countBeen.setMCountDate(time);
            countBeen.setMTime(GetData.getHHmmTimet());
            countBeen.setMShopId(getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));
            countBeen.setMCountName(name);
            countBeen.setMCountSatus("n");
            countBeen.setMCountType("随时");
            countBeen.setMDetail(detail);
            countBeen.setMCountNum(String.valueOf(goodsDtos.size()));
            countBeenDao.insert(countBeen);
            Intent intent = new Intent(this, CountListActivity.class);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "数据为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void setSwipeListView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xD9, 0x47,
                        0x47)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        lv_goods_counts.setMenuCreator(creator);

        // step 2. listener item click event
        lv_goods_counts.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
//                GoodsDto item = goodsDtos.get(position);
//					delete(item);
                goodsDtos.remove(position);
                sAdapter.notifyDataSetChanged();
            }
        });

        // set SwipeListener
        lv_goods_counts.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void search(String code) {
        //搜索
        GoodsDto goodsDto = dao.selectGoods(code);
        if (goodsDto != null) {
            check(goodsDto);
        } else {
            Toast.makeText(this, "商品不存在", Toast.LENGTH_SHORT).show();
//
        }
        et_code_counts.setText("");
        sAdapter.notifyDataSetChanged();
        lv_goods_counts.setFocusable(false);
        ETRequestFocus();

    }
    public void ETRequestFocus() {
        et_code_counts.setFocusable(true);
        et_code_counts.setFocusableInTouchMode(true);
        et_code_counts.requestFocus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == 1) {
                search(data.getStringExtra("code"));
//                judgeCode(data.getStringExtra("code"));
            }
        }
    }

    //    public void searchOrder() {
//        int maxNo;
//        try {
//            maxNo = Integer.parseInt(etOrder.getText().toString().trim());
//            OrderDto selectDto = new OrderDao(getApplicationContext()).selectOrderByNo(maxNo);
//            if (selectDto == null) {
//                showToast("未查询到该订单");
//            } else {
//                orderDtos.clear();
//                orderDtos.add(selectDto);
//                adapter.notifyDataSetChanged();
//            }
//        } catch (Exception e) {
//            showToast("请输入合适的订单号");
//        }
//    }
    private void check(GoodsDto gd){
        for (GoodsDto dto : goodsDtos) {
            if (dto.getSid().equals(gd.getSid())) {
                dto.setNum(DoubleSave.doubleSaveTwo(dto.getNum() + 1));
                return;
            }
        }
        goodsDtos.add(gd);
        this.gd = gd;
        showInput();
    }
    private EditText et_table;
    private void showInput() {
        darkenBackgroud(0.4f);
        et_code_counts.setCursorVisible(false);
        View contentView = View.inflate(this, R.layout.num_item, null
        );
        final PopupWindow popupWindow = new PopupWindow(contentView, getWidth() * 2 / 3, getHeight() * 3 / 5);
        popupWindow.setOutsideTouchable(false);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        TextView sure = (TextView) contentView.findViewById(R.id.sure_table);
        TextView name_table = (TextView) contentView.findViewById(R.id.name_table);
        et_table = (EditText) contentView.findViewById(R.id.et_table);
        TextView clear_table = (TextView) contentView.findViewById(R.id.clear_table);
        name_table.setText(gd.getName());
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                et_code_counts.setCursorVisible(true);
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        et_table.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                et_table.setSelection(et_table.getText().toString().trim().length());
            }
        });

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                darkenBackgroud(1f);
                popupWindow.dismiss();
                if (et_table.getText().toString().trim().isEmpty()) {
                    return;
                }
                gd.setNum(Double.parseDouble(et_table.getText().toString().trim()));
                sAdapter.notifyDataSetChanged();

            }
        });
        clear_table.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_table.setText("");
                numberAdd = "";
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                numberAdd = "";
            }
        });
    }
    private String numberAdd = "";

    public void popupWindowNumberClick(View view) {
        TextView tv = (TextView) view;
        if (numberAdd.isEmpty()) {
            if (view.getId() != R.id.dian) {
                numberAdd += tv.getText().toString();
            }
        } else {
            if (numberAdd.equals("0") && view.getId() == R.id.dian) {
                numberAdd = tv.getText().toString();
            } else {
                numberAdd += tv.getText().toString();
            }
        }
        et_table.setText(numberAdd);
    }
    private int  getWidth(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.widthPixels;
    }
    private  int getHeight(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.heightPixels;
    }
    private void darkenBackgroud(Float bgcolor) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgcolor;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }
}